package com.mzj.saas.redis.listener;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.haixiaoke.saas.repository.pojo.Order;
import com.haixiaoke.saas.repository.pojo.OrderOperatingRecord;
import com.haixiaoke.saas.repository.service.IOrderLockService;
import com.haixiaoke.saas.repository.service.IOrderOperatingRecordService;
import com.haixiaoke.saas.repository.service.IOrderService;
import com.mzj.saas.constant.OrderConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * redis过期监听
 *
 * @author hupeng
 * @since 2020-02-27
 */
@Slf4j
@Component
public class RedisKeyExpirationListener implements MessageListener {


    private String database;
    private RedisTemplate redisTemplate;

    private IOrderService iOrderService;        //订单service
    private IOrderLockService iOrderLockService;
    private IOrderOperatingRecordService iOrderOperatingRecordService;    //订单记录service

    public RedisKeyExpirationListener(RedisTemplate redisTemplate, String database,IOrderService iOrderService, IOrderLockService iOrderLockService,IOrderOperatingRecordService iOrderOperatingRecordService) {
        this.redisTemplate = redisTemplate;
        this.database = database;
        this.iOrderService = iOrderService;
        this.iOrderLockService = iOrderLockService;
        this.iOrderOperatingRecordService = iOrderOperatingRecordService;

    }


    @Override
    public void onMessage(Message message, byte[] bytes) {
        RedisSerializer<?> serializer = redisTemplate.getValueSerializer();
        String channel = String.valueOf(serializer.deserialize(message.getChannel()));
        String body = String.valueOf(serializer.deserialize(message.getBody()));
        //key过期监听
        if (StrUtil.format("__keyevent@{}__:expired", database).equals(channel)) {
            // 订单自动取消
            if (body.contains(OrderConstant.REDIS_ORDER_OUTTIME_UNPAY)) {
                body = body.replace(OrderConstant.REDIS_ORDER_OUTTIME_UNPAY, "");
                Console.log("body:{}", body);
                String orderId = body;
                // 从数据中查order, 只有待支付的订单能取消
                // if(order != null){
                //  orderService.cancelOrder(order.getOrderId());
                //  log.info("订单id:{},未在规定时间支付取消成功",body);
                // }

                Order order = iOrderService.selectOrderById(orderId);
                //order对象不为空，且订单状态为未支付
                if (ObjectUtil.isNotEmpty(order) && Objects.equals(order.getOrderState(), Order.ORDER_STATE_UN_PAYMENT)) {
                    DateTime updateTime = DateUtil.date();
                    //更改订单状态为“已取消”
                    order.setUpdateBy("System");
                    order.setUpdateTime(updateTime);
                    order.setOrderState(Order.ORDER_STATE_CANCELED);
                    int i = iOrderService.updateOrderState(order);
                    if (i != 0) {
                        //记录订单状态变更的操作
                        OrderOperatingRecord record = new OrderOperatingRecord();
                        record.setOrderId(order.getOrderId());      //订单id
                        record.setOrderState(Order.ORDER_STATE_CANCELED); //订单状态
                        record.setOrderSourceState(Order.ORDER_STATE_UN_PAYMENT);
                        record.setOperatingBy("System");
                        record.setOperatingTime(updateTime);   //操作时间
                        record.setRemark(OrderOperatingRecord.RECORD_REMARK_CANCELED);//备注内容
                        iOrderOperatingRecordService.insertOrderOperatingRecord(record);
                        iOrderLockService.deleteOrderLockByOrderId(order.getOrderId());
                        log.info("Order的数据为:{}", JSONObject.toJSONString(order));
                        log.info("OrderOperatingRecord的数据为:{}", JSONObject.toJSONString(record));
                    }
                } else {
                    log.error("订单状态异常，order：{}",order);
                }
            }

        }

    }
}
